#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <7zVersion.h>
#include <LzmaLib.h>

void PrintHelp(char *buffer)
{
  buffer[0] = 0;
  strcat(buffer, "\nLZMA Utility " MY_VERSION_COPYRIGHT_DATE "\n"
      "\nUsage:  lzma <e|d> inputFile outputFile\n"
             "  e: encode file\n"
             "  d: decode file\n");
}

int PrintError(char *buffer, const char *message)
{
  strcat(buffer, "\nError: ");
  strcat(buffer, message);
  strcat(buffer, "\n");
  printf("%s", buffer);
  return 1;
}

int main(int argc, char *argv[])
{
   char rs[1024] = {0,};
  int encodeMode;
  int res;
  char c;

  PrintHelp(rs);
  if (argc < 3 || argc > 4 || strlen(argv[1]) != 1)
  {
      return PrintError(rs, "argument error.");
  }

  c = argv[1][0];
  encodeMode = (c == 'e' || c == 'E');
  if (!encodeMode && c != 'd' && c != 'D') 
  {
     return PrintError(rs, "argument error.");
  }
  if (encodeMode)
      res = LzmaCompressFile(argv[2], argv[3]);
  else 
      res = LzmaUnCompressFile(argv[2], argv[3]);

  if (res != SZ_OK)
  {
    if (res == SZ_ERROR_MEM)
        return PrintError(rs, "Can not allocate memory");
    else if (res == SZ_ERROR_DATA)
        return PrintError(rs, "Data error");
    else if (res == SZ_ERROR_WRITE)
        return PrintError(rs, "Can not write output file");
    else if (res == SZ_ERROR_READ)
        return PrintError(rs, "Can not read input file");
    else if (res == SZ_ERROR_INPUT_EOF)
        return PrintError(rs, "Can not open input file");
    else if (res == SZ_ERROR_OUTPUT_EOF)
        return PrintError(rs, "Can not open output file");
    return -1;
  }
  return 0;
}
